package com.wing.productionPlan.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.utils.JsonResult;
import com.wing.enterprise.product.model.entity.ProductDetail;
import com.wing.productionPlan.dao.ProProductDeliveryOrderDetailDao;
import com.wing.productionPlan.model.entity.ProProductDeliveryOrder;
import com.wing.productionPlan.model.entity.ProProductDeliveryOrderDetail;
import com.wing.productionPlan.model.response.ProProductDeliveryCollectionDetailVo;
import com.wing.productionPlan.model.response.ProProductDeliveryCollectionTwoVo;
import com.wing.productionPlan.model.response.ProProductDeliveryOrderDetailVo;
import com.wing.productionPlan.service.ProProductDeliveryOrderDetailService;
import com.wing.productionPlan.service.ProProductDeliveryOrderService;
import com.wing.web.excel.ProProductOrderExcelln;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


/**
 * 提货订单详情信息-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ProProductDeliveryOrderDetailServiceImpl extends ServiceImpl<ProProductDeliveryOrderDetailDao, ProProductDeliveryOrderDetail> implements ProProductDeliveryOrderDetailService{

    @Autowired
    private ProProductDeliveryOrderService proProductDeliveryOrderService;

    /**
     * 查询提货详情
     * @param pg
     * @param map
     * @return
     */
    @Override
    public Page<ProProductDeliveryOrderDetailVo> pageList4app(Page<ProProductDeliveryOrderDetailVo> pg, Map map) {
        List<ProProductDeliveryOrderDetailVo> tasks = this.baseMapper.pageList4app(pg,map);
        pg.setRecords(tasks);
        return pg;
    }

    /**
     * 修改提货订单详情
     * @param proProductDeliveryOrder
     * @return
     */
    @Override
    public int updateInfo(ProProductDeliveryOrderDetail proProductDeliveryOrder) {
        String orderNo = proProductDeliveryOrder.getOrderNo();
        if (StrUtil.isEmpty(orderNo)){
            return 0;
        }
        Long no = Long.valueOf(orderNo);
        ProProductDeliveryOrder serviceById = proProductDeliveryOrderService.getById(no);
        proProductDeliveryOrder.setUpdateTime(LocalDateTime.now());
        proProductDeliveryOrder.setOrderNo(serviceById.getOrderNo());
        proProductDeliveryOrder.setModifier(JwtUtils.getLoginUserId());
        proProductDeliveryOrder.setModifierName(JwtUtils.getLoginUsername());
        return updateById(proProductDeliveryOrder)?1:0;
    }


    /**
     * 添加提货订单详情
     * @param proProductDeliveryOrder
     * @return
     */
    @Override
    public int add(ProProductDeliveryOrderDetail proProductDeliveryOrder) {
        String orderNo = proProductDeliveryOrder.getOrderNo();
        if (StrUtil.isEmpty(orderNo)){
           return 0;
        }
        Long no = Long.valueOf(orderNo);
        ProProductDeliveryOrder serviceById = proProductDeliveryOrderService.getById(no);
        proProductDeliveryOrder.setCreateTime(LocalDateTime.now());
        proProductDeliveryOrder.setCreator(JwtUtils.getLoginUserId());
        proProductDeliveryOrder.setOrderNo(serviceById.getOrderNo());
        proProductDeliveryOrder.setCreatorName(JwtUtils.getLoginUsername());
        proProductDeliveryOrder.setSendNum(0);
        return save(proProductDeliveryOrder)?1:0;
    }

    /**
     * 汇总
     * @param pg
     * @param map
     * @return
     */
    @Override
    public Page<ProProductDeliveryCollectionTwoVo> pageListCollect4app(Page<ProProductDeliveryCollectionTwoVo> pg, Map map) {
        List<ProProductDeliveryCollectionTwoVo> collectionVos = this.baseMapper.pageListCollect4app(pg,map);
        pg.setRecords(collectionVos);
        return pg;
    }

    /**
     * 按条件查询出提货明细
     * @param map
     * @return
     */
    @Override
    public List<ProProductDeliveryCollectionDetailVo> collectList(Map map) {
        //拿到符合条件的所有数据
        List<ProProductDeliveryCollectionDetailVo> proProductDeliveryCollectionDetailVos = this.baseMapper.collectList(map);
        //按照时间分组

        // 按时间倒序排序，然后按日期分组
        Map<LocalDate, List<ProProductDeliveryCollectionDetailVo>> groupedAndSortedOrders = proProductDeliveryCollectionDetailVos.stream()
                .sorted(Comparator.comparing(ProProductDeliveryCollectionDetailVo::getDeliveryTime).reversed()) // 倒序排序
                .collect(Collectors.groupingBy(
                        ProProductDeliveryCollectionDetailVo::getDeliveryTime // 按日期分组
                ));
        //输出一个新的数据
        List<ProProductDeliveryCollectionDetailVo> list = new ArrayList<>();
        // 输出结果
        if (!CollectionUtil.isEmpty(groupedAndSortedOrders)) {
            groupedAndSortedOrders.forEach((date, orderList) -> {
                ProProductDeliveryCollectionDetailVo vo = new ProProductDeliveryCollectionDetailVo();
                vo.setDeliveryTime(date);
                AtomicReference<Integer> sendNums = new AtomicReference<>(0);
                AtomicReference<Integer> deliveryNums = new AtomicReference<>(0);
                Set<String> orders = new HashSet<>();
                if (!CollectionUtil.isEmpty(orderList)) {
                    orderList.forEach(info -> {
                        sendNums.updateAndGet(v -> v + info.getSendNums());
                        deliveryNums.updateAndGet(v -> v + info.getDeliveryNums());
                        orders.add(info.getOrderNo());
                    });
                    vo.setSendNums(sendNums.get());
                    vo.setDeliveryNums(deliveryNums.get());
                    vo.setOrderNums(orders.size());
                }
                list.add(vo);
            });
        }
        return list;
    }


    /**
     * 导入excel
     * @param list
     */
    @Override
    public JsonResult importExcel(List<ProProductOrderExcelln> list, String orderNo, LocalDate deliveryTime) {
        if (StrUtil.isEmpty(orderNo)){
            return JsonResult.fail("请选择提货订单！");
        }
        if (null == deliveryTime){
            return JsonResult.fail("请选择提货时间！");
        }
        //查询当前的 redis 拿到所有的 code-> id map
        ProProductDeliveryOrder deliveryOrder = proProductDeliveryOrderService.getById(orderNo);
        List<Map<String,Object>> map = proProductDeliveryOrderService.getCodeToIdMapForProduct();
        List<ProProductDeliveryOrderDetail> details = new ArrayList<>();
        list.stream().forEach(info->{
            ProProductDeliveryOrderDetail orderDetail = new ProProductDeliveryOrderDetail();
            if (StrUtil.isNotEmpty(info.getSkuCode())){
                map.forEach(res->{
                    if (null != res.get("sku_code")&& res.get("sku_code").toString().equals(info.getSkuCode())){
                        orderDetail.setOrderNo(deliveryOrder.getOrderNo());
                        orderDetail.setProductDetailId(Long.valueOf(res.get("id").toString()));
                        orderDetail.setDeliveryNum(info.getDeliveryNum());
                        orderDetail.setSendNum(0);
                        orderDetail.setRemark(info.getRemark());
                        orderDetail.setDeliveryNature("2");
                        orderDetail.setCustomerId(deliveryOrder.getCustomerId());
                        orderDetail.setDeliveryTime(deliveryTime);
                        orderDetail.setProductionLine(info.getProductionLine());
                        orderDetail.setUnitName(info.getCgRemark());
                        orderDetail.setCreateTime(LocalDateTime.now());
                        orderDetail.setCreator(JwtUtils.getLoginUserId());
                        orderDetail.setCreatorName(JwtUtils.getLoginUsername());
                        orderDetail.setStatus("1");
                        details.add(orderDetail);
                    }
                });
            }
        });
        boolean b = saveBatch(details);
        if (b){
            return JsonResult.success();
        }else {
            return JsonResult.fail("导入失败！");
        }
    }
}
